<template>
  <div class="allocation-container">
    <div class="header">
      <button class="nav-button" @click="goToPreviousStep">上一步</button>
      <div class="steps-container">
        <div v-for="(step, index) in steps" :key="step" :class="['step-box', { active: index === 0 }]">
          {{ step }}
        </div>
      </div>
      <button class="nav-button" @click="goToNextStep">下一步</button>
    </div>

    <div class="table-container">
      <el-form ref="formRef" :model="params" :rules="rules" label-width="140px" label-position="top">
        <div class="table-header">
          <span class="table-title">分配参数配置</span>
          <div class="button-group">
            <el-button @click="goToPreviousStep">返回分配方法选择</el-button>
            <el-button type="primary" @click="handleSave">保存配置</el-button>
          </div>
        </div>

        <!-- 总能耗部分 -->
        <div class="param-card total-energy">
          <div class="card-header">
            <h3>总能耗</h3>
          </div>
          <div class="card-content">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="水能" prop="totalEnergy.waterUsage">
                  <el-input v-model="params.totalEnergy.waterUsage" type="number">
                    <template #append>m³</template>
                  </el-input>
                </el-form-item>
                <el-form-item label="天然气" prop="totalEnergy.gasUsage">
                  <el-input v-model="params.totalEnergy.gasUsage" type="number">
                    <template #append>m³</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="电能" prop="totalEnergy.electricityUsage">
                  <el-input v-model="params.totalEnergy.electricityUsage" type="number">
                    <template #append>kWh</template>
                  </el-input>
                </el-form-item>
                <el-form-item label="柴油" prop="totalEnergy.oilUsage">
                  <el-input v-model="params.totalEnergy.oilUsage" type="number">
                    <template #append>L</template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>

        <div class="params-grid">
          <!-- 组织层参数 -->
          <div class="param-card" v-if="selectedMethods.organization">
            <div class="card-header">
              <h3>组织层参数</h3>
              <el-tag>{{ selectedMethods.organization }}</el-tag>
            </div>
            <div class="card-content">
              <template v-if="selectedMethods.organization === '预估能耗'">
                <el-form-item label="生产能耗" prop="organizationLayer.parameters.productionEnergy">
                  <el-input v-model="params.organizationLayer.parameters.productionEnergy" type="number">
                    <template #append>kWh</template>
                  </el-input>
                </el-form-item>
                <el-form-item label="办公能耗" prop="organizationLayer.parameters.officeEnergy">
                  <el-input v-model="params.organizationLayer.parameters.officeEnergy" type="number">
                    <template #append>kWh</template>
                  </el-input>
                </el-form-item>
              </template>
              <template v-else-if="selectedMethods.organization === '专家意见'">
                <div class="slider-box">
                  <span>分配比例：{{ params.organizationLayer.parameters.expertPercentage }}%</span>
                  <el-slider
                    v-model="params.organizationLayer.parameters.expertPercentage"
                    :format-tooltip="value => `${value}%`"
                  />
                </div>
              </template>
            </div>
          </div>

          <!-- 产线层参数 -->
          <div class="param-card" v-if="selectedMethods.productionLine">
            <div class="card-header">
              <h3>产线层参数</h3>
              <el-tag type="success">{{ selectedMethods.productionLine }}</el-tag>
            </div>
            <div class="card-content">
              <template v-if="selectedMethods.productionLine === '产品产量'">
                <el-form-item label="产品产量" prop="productionLineLayer.parameters.productQuantity">
                  <el-input v-model="params.productionLineLayer.parameters.productQuantity" type="number" />
                </el-form-item>
                <el-form-item label="所有产品产量" prop="productionLineLayer.parameters.totalProductQuantity">
                  <el-input v-model="params.productionLineLayer.parameters.totalProductQuantity" type="number" />
                </el-form-item>
              </template>
              <template v-else-if="selectedMethods.productionLine === '专家意见'">
                <div class="slider-box">
                  <span>分配比例：{{ params.productionLineLayer.parameters.expertPercentage }}%</span>
                  <el-slider
                    v-model="params.productionLineLayer.parameters.expertPercentage"
                    :format-tooltip="value => `${value}%`"
                  />
                </div>
              </template>
            </div>
          </div>

          <!-- 产品层参数 -->
          <div class="param-card" v-if="selectedMethods.product">
            <div class="card-header">
              <h3>产品层参数</h3>
              <el-tag type="warning">{{ selectedMethods.product }}</el-tag>
            </div>
            <div class="card-content">
              <template v-if="selectedMethods.product === '产品产量'">
                <el-form-item label="产品产量" prop="productLayer.parameters.productQuantity">
                  <el-input v-model="params.productLayer.parameters.productQuantity" type="number" />
                </el-form-item>
                <el-form-item label="所有产品产量" prop="productLayer.parameters.totalProductQuantity">
                  <el-input v-model="params.productLayer.parameters.totalProductQuantity" type="number" />
                </el-form-item>
              </template>
              <template v-else-if="selectedMethods.product === '产品生产时长'">
                <el-form-item label="产品加工时长" prop="productLayer.parameters.productProcessingTime">
                  <el-input v-model="params.productLayer.parameters.productProcessingTime" type="number">
                    <template #append>小时</template>
                  </el-input>
                </el-form-item>
                <el-form-item label="产品总加工时长" prop="productLayer.parameters.totalProcessingTime">
                  <el-input v-model="params.productLayer.parameters.totalProcessingTime" type="number">
                    <template #append>小时</template>
                  </el-input>
                </el-form-item>
              </template>
            </div>
          </div>

          <!-- 设备层参数 -->
          <div class="param-card" v-if="selectedMethods.equipment">
            <div class="card-header">
              <h3>设备层参数</h3>
              <el-tag type="info">预估能耗</el-tag>
            </div>
            <div class="card-content">
              <el-table
                :data="params.equipmentLayer.equipmentList"
                style="width: 100%; height: 200px; overflow-y: auto"
                :scrollbar-always-on="true"
              >
                <el-table-column prop="equipmentName" label="设备名称" />
                <el-table-column label="设备预估能耗">
                  <template #default="{ row, $index }">
                    <el-form-item
                      :prop="`equipmentLayer.equipmentList.${$index}.estimatedEnergy`"
                      :rules="{
                        required: true,
                        message: '请输入设备预估能耗',
                        trigger: 'blur'
                      }"
                    >
                      <el-input v-model="row.estimatedEnergy" type="number">
                        <template #append>kWh</template>
                      </el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="所有设备预估能耗">
                  <template #default="{ row, $index }">
                    <el-form-item
                      :prop="`equipmentLayer.equipmentList.${$index}.totalEstimatedEnergy`"
                      :rules="{
                        required: true,
                        message: '请输入所有设备预估能耗',
                        trigger: 'blur'
                      }"
                    >
                      <el-input v-model="row.totalEstimatedEnergy" type="number">
                        <template #append>kWh</template>
                      </el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ElMessage } from "element-plus";
import { ref, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { energyAllocationResponse } from "@/assets/mock/mockData";
import type { Allocation } from "@/api/interface";
import axios from "axios";
import { useTabsStore } from "@/stores/modules/tabs";
const tabStore = useTabsStore();

const router = useRouter();
const route = useRoute();
const projectId = route.params.projectId;

// 步骤
const steps = ["分配参数配置", "选择碳排放因子", "碳足迹计算结果"];

// 获取选择的分配方法
const selectedMethods = ref(JSON.parse(localStorage.getItem(`allocationMethods_${projectId}`) || "{}"));

// 仅从 localStorage 读取已保存的参数，如无则初始化默认结构
const params = ref<Allocation.AllocationList>(
  JSON.parse(localStorage.getItem(`allocationParams_${projectId}`) || "null") || {
    projectId: projectId as string,
    totalEnergy: {
      waterUsage: null,
      electricityUsage: null,
      gasUsage: null,
      oilUsage: null
    },
    organizationLayer: {
      method: null,
      parameters: {
        productionEnergy: null,
        officeEnergy: null,
        expertPercentage: 50
      }
    },
    productionLineLayer: {
      method: null,
      parameters: {
        productQuantity: null,
        totalProductQuantity: null,
        expertPercentage: 50
      }
    },
    productLayer: {
      method: null,
      parameters: {
        productQuantity: null,
        totalProductQuantity: null,
        productProcessingTime: null,
        totalProcessingTime: null
      }
    },
    equipmentLayer: {
      method: null,
      equipmentList: []
    }
  }
);

// 在组件挂载时同步设备列表
onMounted(() => {
  fetchAndSyncEquipmentList();
});

// 获取后端设备列表并与缓存对比，不新增减少则保持界面不变
const fetchAndSyncEquipmentList = async () => {
  try {
    const res = await axios.get(baseUrl + "/api/carbon/projectEquipmentList", {
      params: { projectId }
    });
    console.log("后端返回设备列表：", res.data);
    if (res.data?.code !== 200) {
      ElMessage({ type: "error", message: "获取设备列表失败" });
      return;
    }
    const apiEquipList: { equipmentId: number | string; equipmentName: string }[] = res.data?.data || [];

    const apiIds = apiEquipList.map(item => item.equipmentId);

    const savedAllocationStr = localStorage.getItem(`allocationParams_${projectId}`);
    let savedEquipIds: Array<number | string> = [];

    if (savedAllocationStr) {
      const savedAllocation = JSON.parse(savedAllocationStr);
      savedEquipIds =
        savedAllocation.equipmentLayer?.equipmentList?.map((eq: { equipmentId: number | string }) => eq.equipmentId) || [];
    }
    const isSame = apiIds.length === savedEquipIds.length && apiIds.every(id => savedEquipIds.includes(id));
    if (!isSame) {
      console.log("设备列表有变化，更新界面");
      params.value.equipmentLayer.equipmentList = apiEquipList.map(item => ({
        equipmentId: item.equipmentId,
        equipmentName: item.equipmentName,
        estimatedEnergy: null,
        totalEstimatedEnergy: null
      }));
    } else if (savedAllocationStr) {
      // 若列表一致且本地有缓存，直接使用缓存中的设备能耗数据
      params.value.equipmentLayer.equipmentList = JSON.parse(savedAllocationStr).equipmentLayer.equipmentList;
    }
  } catch (error) {
    console.error("获取设备列表失败：", error);
  }
};

const formRef = ref();
const baseUrl = import.meta.env.VITE_BASE_URL;
// 表单验证规则
const rules = {
  "totalEnergy.waterUsage": [{ required: true, message: "请输入用水量", trigger: "blur" }],
  "totalEnergy.electricityUsage": [{ required: true, message: "请输入用电量", trigger: "blur" }],
  "totalEnergy.gasUsage": [{ required: true, message: "请输入天然气用量", trigger: "blur" }],
  "totalEnergy.oilUsage": [{ required: true, message: "请输入柴油用量", trigger: "blur" }],
  // 组织层参数验证
  "organizationLayer.parameters.productionEnergy": [
    { required: selectedMethods.value.organization === "预估能耗", message: "请输入生产能耗", trigger: "blur" }
  ],
  "organizationLayer.parameters.officeEnergy": [
    { required: selectedMethods.value.organization === "预估能耗", message: "请输入办公能耗", trigger: "blur" }
  ],
  "organizationLayer.parameters.expertPercentage": [
    { required: selectedMethods.value.organization === "专家意见", message: "请设置分配比例", trigger: "change" }
  ],
  // 产线层参数验证
  "productionLineLayer.parameters.productQuantity": [
    { required: selectedMethods.value.productionLine === "产品产量", message: "请输入产品产量", trigger: "blur" }
  ],
  "productionLineLayer.parameters.totalProductQuantity": [
    { required: selectedMethods.value.productionLine === "产品产量", message: "请输入所有产品产量", trigger: "blur" }
  ],
  "productionLineLayer.parameters.expertPercentage": [
    { required: selectedMethods.value.productionLine === "专家意见", message: "请设置分配比例", trigger: "change" }
  ],
  // 产品层参数验证
  "productLayer.parameters.productQuantity": [
    { required: selectedMethods.value.product === "产品产量", message: "请输入产品产量", trigger: "blur" }
  ],
  "productLayer.parameters.totalProductQuantity": [
    { required: selectedMethods.value.product === "产品产量", message: "请输入所有产品产量", trigger: "blur" }
  ],
  "productLayer.parameters.productProcessingTime": [
    { required: selectedMethods.value.product === "产品生产时长", message: "请输入产品加工时长", trigger: "blur" }
  ],
  "productLayer.parameters.totalProcessingTime": [
    { required: selectedMethods.value.product === "产品生产时长", message: "请输入产品总加工时长", trigger: "blur" }
  ]
};
const fetchEnergyAllocation = async (requestData: any) => {
  try {
    console.log("请求数据：", requestData);
    const response = await axios.post(baseUrl + "/api/carbon/productAllocation2", requestData);
    console.log("后端返回分配结果：", response.data);

    energyAllocationResponse.value = response.data.data.processes || [];
    console.log("energyAllocationResponse", energyAllocationResponse.value);

    // 获取并更新碳排放数据
    const storageKey = `processCarbonEmission_${projectId}`;
    const savedData = localStorage.getItem(storageKey);
    if (savedData) {
      const carbonEmissionData = JSON.parse(savedData);
      const updatedData = fillAllocationData(carbonEmissionData);
      localStorage.setItem(storageKey, JSON.stringify(updatedData));
    }
  } catch (err) {
    console.error("调用接口失败：", err);
  }
};

// 填充分配获取的能耗数据
const fillAllocationData = (carbonEmissionData: any) => {
  // 格式化数字，保留两位小数，整数不显示小数点
  const formatNumber = (num: string) => {
    const parsed = parseFloat(num);
    return Number.isInteger(parsed) ? parsed.toString() : parsed.toFixed(2);
  };

  carbonEmissionData.forEach((chart: any) => {
    chart.nodes?.forEach((node: any) => {
      node.inputNodes?.forEach((input: any) => {
        if (input.dataSource === "分配获取") {
          // 在能耗分配响应中查找对应的工序数据
          const processData = energyAllocationResponse.value.find(item => item.processName === node.process?.processName);

          if (processData) {
            // 查找对应类型的输入能耗数据
            const allocationInput = processData.allocationInput.find(item => item.inputType === input.inputType);

            if (allocationInput) {
              // 填充能耗值和单位，格式化数字
              input.inputConsumption = formatNumber(allocationInput.inputConsumption);
              input.inputUnit = allocationInput.inputUnit;
            }
          }
        }
      });
    });
  });
  return carbonEmissionData;
};

// 保存配置
const handleSave = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();

    // 直接从 localStorage 获取工艺碳排放清单数据
    const savedData = localStorage.getItem(`processCarbonEmission_${projectId}`);
    if (savedData) {
      const carbonEmissionData = JSON.parse(savedData);

      // 从所有节点中提取工序名称，并去重
      const newProcessNames = [
        ...(Array.from(
          new Set(
            carbonEmissionData
              .flatMap(
                (chart: {
                  nodes?: {
                    process?: { processName?: string };
                    inputNodes?: { dataSource?: string }[];
                  }[];
                }) => {
                  const filteredNodes =
                    chart.nodes
                      ?.filter(node => {
                        const hasAllocationInput = node.inputNodes?.some(input => input.dataSource === "分配获取");
                        return hasAllocationInput;
                      })
                      .map(node => node.process?.processName) || [];
                  return filteredNodes;
                }
              )
              .filter(Boolean)
          )
        ) as string[])
      ];

      // 更新 params 中的工序名称列表
      params.value = {
        ...params.value,
        processNames: newProcessNames
      };
    }

    // 保存配置
    localStorage.setItem(`allocationParams_${projectId}`, JSON.stringify(params.value));

    // 调用接口获取分配数据
    await fetchEnergyAllocation(params.value);

    ElMessage({
      type: "success",
      message: "保存配置成功"
    });
  } catch (error) {
    ElMessage({
      type: "error",
      message: "请完善必填项"
    });
  }
};

// 上一步
const goToPreviousStep = () => {
  if (route.meta.isAffix) return;
  tabStore.removeTabs(route.fullPath);
  router.push(`/lca/impact/allocation/${projectId}`);
};

// 下一步
const goToNextStep = () => {
  if (route.meta.isAffix) return;
  tabStore.removeTabs(route.fullPath);
  router.push(`/lca/impact/index/${projectId}`);
};
</script>

<style scoped>
.total-energy {
  margin: 0 20px 20px;
}
.params-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
  padding: 20px;
}
.param-card {
  height: 250px;
  padding: 20px;
  background: #ffffff;
  border: 1px solid var(--el-border-color-light);
  border-radius: 8px;
}
.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}
.card-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}
.card-content {
  padding: 16px 0;
}
.slider-box {
  padding: 20px;
}
.slider-box span {
  display: block;
  margin-bottom: 12px;
}
:deep(.el-form-item__label) {
  font-weight: 500;
}
:deep(.el-input-group__append) {
  padding: 0 12px;
}

/* 继承原有的 header 和基础样式 */
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 20px;
  margin-bottom: 16px;
  background-color: #ffffff;
  border-bottom: 1px solid #dddddd;
  border-radius: 8px;
}
.table-container {
  padding: 20px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
}
.table-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-bottom: 12px;
  margin-bottom: 20px;
  border-bottom: 1px solid var(--el-border-color-light);
}
.table-title {
  font-size: 18px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}
.total-energy-section {
  width: calc(100% - 40px); /* 减去左右padding的20px */
  padding: 20px;
  margin-right: 20px; /* 与params-grid对齐 */
  margin-bottom: 24px;
  margin-left: 20px; /* 与params-grid对齐 */
  background: #ffffff;
  border: 1px solid var(--el-border-color-light);
  border-radius: 8px;
}
.energy-inputs {
  margin-top: 16px;
}
.section-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}
.nav-button {
  padding: 10px 20px;
  font-size: 16px;
  color: white;
  cursor: pointer;
  background-color: #009688;
  border: none;
  border-radius: 5px;
  transition: background-color 0.3s;
}
.nav-button:hover {
  background-color: #007d6a;
}
.steps-container {
  display: flex;
  justify-content: space-between;
  width: 80%;
  padding: 0 20px;
}
.step-box {
  position: relative;
  flex: 1;
  padding: 15px 10px;
  margin: 0 10px;
  color: #777777;
  text-align: center;
  cursor: pointer;
  background-color: #f9f9f9;
  border: 1px solid #dcdcdc;
  border-radius: 5px;
  transition: all 0.3s;
}
.step-box.active {
  font-weight: bold;
  color: #009688;
  background-color: #e6f5f3;
  border-color: #009688;
}
.step-box::after {
  position: absolute;
  top: 50%;
  right: -20px;
  font-size: 20px;
  color: #009688;
  content: "→";
  transform: translateY(-50%);
}
.step-box:last-child::after {
  visibility: hidden;
}
.button-group {
  display: flex;
  gap: 12px;
}
</style>
